import os,shutil,io
import fitz
import chardet
class PdfUtil:
    def __init__(self):
        pass
    @staticmethod
    def open(filename:str,password:str=None)->fitz.Document:
        '''
        打开一个pdf文档
        :param filename:要打开的pdf文件路径
        :param password:密码
        :return: 返回fitz.Document
        '''
        print(fitz.version)
        doc:fitz.Document=fitz.open(filename)
        if doc.isEncrypted:
            doc.authenticate(password)
        return doc

    @staticmethod
    def ConvertToPdf(filename:str,newfilepath:str):
        '''
           转发html,epub,pdf,doc等为pdf
           filename为源文件
           newfilepath为生成pdf的目录
           :param filename: 为源文件
           :param newfilepath:为生成pdf的目录
           '''
        img=PdfUtil.open(filename)
        pdfbytes=img.convertToPDF()
        if not os.path.exists(newfilepath):
            os.makedirs(newfilepath)
        with open(newfilepath+r"/"+os.path.splitext(os.path.split(filename)[1])[0]+".pdf",'wb') as f:
            f.write(pdfbytes)

    @staticmethod
    def ConvertTxtToPdf(filename:str,newfilepath:str):
        '''
            转换txt为pdf
            newfilepath为生成pdf的目录
            '''
        with open(filename,'r',encoding=PdfUtil.detectCode(filename)) as f:
            textlist=f.readlines()
            html='''
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<html lang="zh-cn">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>$txtName$</title>
</head>
<body>
<h1>$txtName$</h1>
<div id="content">
    <p>$content$</p>
    
</div>
</body>
</html>
            '''
            content=''
            for i,text in enumerate(textlist):
                content=content+text+"<br />"
            html= html.replace("$txtName$",filename).replace("$content$",content)
        with open("convert"+".html",'w',encoding='utf-8')as f:
            f.write(html)
            print(f)
        PdfUtil.ConvertToPdf("convert.html","out")
        os.remove("convert.html")

    @staticmethod
    def detectCode(path):
        '''
            检测文本编码
            '''
        with open(path, 'rb') as file:
            data = file.read(1000)
            dicts = chardet.detect(data)
        return dicts["encoding"]
    @staticmethod
    def TxtToHtml(filename:str,newfilepath:str)->str:
        '''
                    转换txt为html
                    newfilepath为生成html的目录
                    :return 生成的html的路径
                    '''
        with open(filename, 'r', encoding=PdfUtil.detectCode(filename)) as f:
            textlist = f.readlines()
            html = '''
                    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
        <html lang="zh-cn">
        <head>
            <meta http-equiv="content-type" content="text/html; charset=utf-8" />
            <title>$txtName$</title>
        </head>
        <body>
        <h1>$txtName$</h1>
        <div id="content">
            <p>$content$</p>

        </div>
        </body>
        </html>
                    '''
            content = ''
            for i, text in enumerate(textlist):
                content = content + text + "<br />"
            html = html.replace("$txtName$", filename).replace("$content$", content)
        with open(newfilepath+r"/"+os.path.splitext(os.path.split(filename)[1])[0]+".html", 'w', encoding='utf-8')as f:
            f.write(html)
        return newfilepath+r"/"+os.path.splitext(os.path.split(filename)[1])[0]+".html"
    @staticmethod
    def pdfTohtml(doc:fitz.Document,newfilepath:str):
        allhtml=io.StringIO("")
        #获取总页码
        pagecount=doc.pageCount
        #获取目录
        #遍历pdf页面,转化成html,然后拼接到一个页面
        for i, page in enumerate(doc.pages()) :
            html=page.getText("html").replace('<div id="page0"','<div id="page'+str(i+1)+'"')
            allhtml.write(html)
        with open(newfilepath + r"/" + os.path.splitext(os.path.split(doc.name)[1])[0] + ".html", 'w',
                  encoding='utf-8') as f:
            f.write(allhtml.getvalue())

    @staticmethod
    def getPageimage(doc:fitz.Document,pagenum:int):
        page:fitz.Page=doc[pagenum]
        return page.getPixmap()
    @staticmethod
    def getMulu(doc:fitz.Document):
        print(doc.getToC())

if __name__ == '__main__':
    doc=PdfUtil.open(r"J:\gif图库\H漫\合集\漫画\02、妖女之祸\PDF格式，无需解压\1-41.pdf")
    print(doc.pageCount)
    print(doc.authenticate("caibudao159753"))
    print(PdfUtil.pdfTohtml(doc,"out"))



